package models

import "time"
import "errors"

// MakeGoods 采购订单详细产品表
type MakeGoods struct {
	GoodsID    string
	Quantity   uint
	MakePerson string
	CreatedAt  time.Time
}

type MakeGoodsInfo struct {
	GoodsID    string
	Quantity   uint
	MakePerson string
	CreatedAt  time.Time
	ID         string
	Name       string
	No         string
}

// CreateMakeMsg 制作
func CreateMakeMsg(goods []MakeGoods) error {
	tx := db.Begin()

	for _, v := range goods {
		v.CreatedAt = time.Now()
		err := tx.Table("make_goods").Create(&v).Error
		if err != nil {
			tx.Rollback()
			return err
		}
		// 更新下成品的库存量
		number, err := getNumber(tx, v.GoodsID)
		if err != nil {
			tx.Rollback()
			return err
		}
		err = updateNumber(tx, v.GoodsID, number+v.Quantity)
		if err != nil {
			tx.Rollback()
			return err
		}
		// 拿出商品的配件比，更新配件的库存量
		commodityComponents := []CommodityComponents{}
		_ = db.Table("commodity_components").Where("commodity_id= ?", v.GoodsID).Find(&commodityComponents)
		for _, commodityComponent := range commodityComponents {
			component := GetComponent(commodityComponent.ComponentID)
			componentNumber := component.Number
			if componentNumber < (commodityComponent.Number * v.Quantity) {
				tx.Rollback()
				return errors.New("配件编号为【" + component.No + "】的库存量不足以制作成品，请确认！")
			}
			err = updateComponentNumber(tx, commodityComponent.ComponentID, componentNumber-commodityComponent.Number)
			if err != nil {
				tx.Rollback()
				return err
			}
		}
	}

	tx.Commit()
	return nil
}

// GetMakeInfo 所有制作
func GetMakeInfo() (goods []MakeGoodsInfo, err error) {
	err = db.Raw(`select t2.id,t2.name,t2.no,t1.goods_id, t1.created_at, t1.quantity, t1.make_person from make_goods as t1 left outer join 
				commodities as t2 on t1.goods_id = t2.id order by t1.created_at desc`).Scan(&goods).Error
	if err != nil {
		return
	}
	return
}
